package com.ccpjcmjs.utils;


import com.ccpjcmjs.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class HtmlParseUtil {

    public static void main(String[] args) throws IOException {
        new HtmlParseUtil().parseJD("vue").forEach(System.out::println);
    }

    public List<Content> parseJD(String keywords) throws IOException{
        //获得请求 https://search.jd.com/Search?keyword=java
        String url = "https://search.jd.com/Search?keyword="+keywords+"&enc=utf-8&wq=java&pvid=45300e220a174eeea886ca4211d102bf";
        //解析网页 (返回的就是浏览器的Document对象)
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        //获取所有的li元素
        Elements elements = element.getElementsByTag("li");
        //获取元素中的内容,这里的el就是li标签

        ArrayList<Content> goodsList = new ArrayList<>();

        for (Element el : elements) {
            //关于图片 特别多的网站都是延迟加载的
            // 图片真正存放位置 source-data-lazy-img
            if (el.attr("class").equalsIgnoreCase("gl-item")){
                String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
                String price = el.getElementsByClass("p-price").eq(0).text();
                String title = el.getElementsByClass("p-name").eq(0).text();
                Content content = new Content(title, img, price);
                goodsList.add(content);
            }
        }
        return goodsList;
    }
}
